package dict

import (
	"context"
	"encoding/json"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/blog-zero/api/admin/internal/types"
	"github.com/blog-zero/rpc/sys/sysclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type DictChildenUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDictChildenUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DictChildenUpdateLogic {
	return &DictChildenUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DictChildenUpdateLogic) DictChildenUpdate(req *types.UpdateDictChildenReq) (*types.UpdateDictChildenResp, error) {
	_, err := l.svcCtx.DictService.DictChildenUpdate(l.ctx, &sysclient.DictChildenUpdateReq{
		Id:          req.Id,
		ParentId:    req.ParentId,
		Label:       req.Label,
		Value:       req.Value,
		Description: req.Description,
		Sort:        req.Sort,
		UpdateBy:    l.ctx.Value("userName").(string),
		Remarks:     req.Remarks,
		Status:      req.Status,
	})

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("更新子字典信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, errorx.NewDefaultError("更新子字典失败")
	}

	return &types.UpdateDictChildenResp{
		Code:    "000000",
		Message: "更新字典成功",
	}, nil
}
